#Alexander F. Gazmararian
# afg2@princeton.edu

library(tidyverse)
library(modelsummary)
library(ggpubr)
library(scales)

source("code/fun/savefig.r")
source("code/fun/book_theme.r")
source("code/fun/fix_txt.r")

g <- readRDS("data/FairGazmararian_2021.rds")

#Create figure 4.4 ----
durability.pid <-
  g %>%
  group_by(messenger, partysummary) %>%
  summarise(n = sum(weights)) %>%
  group_by(partysummary) %>%
  mutate(pct=prop.table(n)) %>%
  filter(partysummary!="Neither") %>%
  ggplot(aes(x=messenger, y=pct, group=partysummary, fill=partysummary, label=percent(pct,accuracy=1))) +
  geom_col(position = "dodge") +
  geom_text(position=position_dodge(.9), vjust=-.5, size =3) +
  scale_fill_grey(name = "") +
  scale_y_continuous(labels = percent_format(accuracy = 1), limits = c(0, .5), expand = c(0,0)) +
  scale_x_discrete(labels = label_wrap(10)) +
  labs(x = "", y = "", subtitle = "Party Identification") +
  book_theme +
  theme(legend.position = "bottom",legend.box.margin = margin(-20), plot.margin=margin(5))
durability.pid

durability.fossil <-
  g %>%
  filter(!is.na(fossil)) %>%
  group_by(messenger, fossil) %>%
  summarise(n = sum(weights)) %>%
  group_by(fossil) %>%
  mutate(pct=prop.table(n)) %>%
  ggplot(aes(x=messenger, y=pct, group=fossil, fill=fossil, label=percent(pct,accuracy=1))) +
  geom_col(position = "dodge") +
  geom_text(position=position_dodge(.9), vjust=-.5, size =3) +
  scale_fill_grey(name = "") +
  scale_y_continuous(labels = percent_format(accuracy = 1), limits = c(0, .5), expand = c(0,0)) +
  scale_x_discrete(labels = label_wrap(10)) +
  labs(x = "", y = "", subtitle = "Fossil Fuel Employment") +
  book_theme +
  theme(legend.position = "bottom",legend.box.margin = margin(-20), plot.margin=margin(5))
durability.fossil
durability.plot <- ggarrange(durability.pid, durability.fossil)
savefig(durability.plot, "4.4_figure_fairdurability", height = 2, filepath = "figures/")


# Estimate linear model for online appendix  ---------------------------------------------------
dur <- list()
dur[[1]] <- lm(duration_scale ~ age + race_acs + partysummary + politician + ffemploy + sex, g, weight = weights)
dur[[2]] <- lm(duration_scale ~ age + race_acs + partysummary + politician + ffemploy + sex + union  + fulltime, g, weight = weights)
dur[[3]] <- lm(duration_scale ~ age + race_acs + partysummary + politician + gw_binary + ffemploy + sex + union + fulltime, g, weight = weights)
dur[[4]] <- lm(duration_scale ~ age + race_acs + partysummary + income_acs + politician + gw_binary + ffemploy + sex + union + fulltime, g, weight = weights)
file <- "tables/ch4/ols_countyfair21_durability.txt"
modelsummary(dur, vcov = "HC2",stars = c("*"=.1,"**"=.05,"***"=.01), coef_map = coefnames,
             gof_map = c("nobs", "adj.r.squared"),
             escape=FALSE,
             output = "latex") %>%
  cat(., file = file)
fix_txt(file)
